<template>
	<view class="content">
		<view class="avatorWrapper">
			<view class="avator">
				<image class="img" src="https://www.cdn.kxcdedu.top/image/default/B96815CBEFBE481984ECAF4B1330CE67-6-2.png"
					mode="widthFix"></image>
			</view>
		</view>
		<view style="margin-top: 40rpx;font-size: 50rpx;letter-spacing: 5rpx;display: flex;flex-direction: row;">欢迎来到
			<view style="font-weight: bold;font-size: 50rpx;">候浪hula</view>
		</view>

		<view style="display: flex;flex-direction: column;align-items: center;" v-if="way == 0">
			<view
				style="margin-top: 400rpx;font-size: 36rpx;color: white;padding: 30rpx 60rpx;background-color: #5DACB1;border-radius: 20rpx;"
				@click="submitlogin()">本机号码一键登录</view>
			<view style="margin-top: 160rpx;color: gray;" @click="changeLoginWay(1)">其他登录方式</view>
		</view>

		<view class="form" v-if="way == 1">
			<view class="inputWrapper">
				<input class="input" style="background-color: #f5f5f5 !important;" type="number" v-model="tel"
					placeholder="请输入手机号" />
			</view>
			<view class="inputWrapper">
				<input type="number" class="input" style="background-color: #f5f5f5 !important;" v-model="code"
					placeholder="请输入验证码" />
			</view>
			<view class="changeWayBtn">
				<text @click="changeLoginWay(2)">账号密码登录</text>
				<text @click="onSMSSend()">{{ getSendBtnText}}</text>
			</view>
			<view class="loginBtn" @click="phoneLogin()">
				<text class="btnValue">登录</text>
			</view>
		</view>


		<view class="form" v-if="way == 2">
			<view class="inputWrapper">
				<input class="input" style="background-color: #f5f5f5 !important;" type="text" v-model="tel"
					placeholder="请输入手机号或账号" />
			</view>
			<view class="inputWrapper">
				<input class="input" style="background-color: #f5f5f5 !important;" type="password" v-model="password"
					placeholder="请输入密码" />
			</view>
			<view class="changeWayBtn">
				<text @click="changeLoginWay(1)">验证码登录</text>
				<text @click="">找回密码</text>
			</view>
			<view class="loginBtn" @click="accountLogin()">
				<text class="btnValue">登录</text>
			</view>
		</view>

		<view v-if="way != 0" style="display: flex;flex-direction: row;justify-content: center;margin-top: 100rpx;"
			@click="wxLogin()">
			<image mode="aspectFill" style="width: 80rpx;height: 80rpx;border-radius: 50%;"
				src="https://upload.shejihz.com/2019/03/c06dbe91d12c4faca4f30b0596df0247.jpg_auto25xauto"></image>
		</view>

		<view style="font-size: 28rpx;color: gray;width: 670rpx;margin-top: 100rpx;">
			登录则代表同意
			<text style="color: #2c2c2c;font-weight: bold;">《候浪用户协议》</text>和
			<text style="color: #2c2c2c;font-weight: bold;">《联通统一认证服务条款》</text>和
			<text style="color: #2c2c2c;font-weight: bold;">《候浪隐私协议》</text>
		</view>

	</view>
</template>

<script>
	import http from '@/common/service/service.js';
	import {
		ACCESS_TOKEN
	} from '@/common/util/constants.js'
	import {
		mapActions
	} from "vuex";
	import {
		genTestUserSig
	} from "../../debug/GenerateTestUserSig";

	export default {
		data() {
			return {
				way: 0,
				tel: '',
				code: null,
				password: '',
				autoStatus: true,
				smsCountDown: 0, // 验证码倒计时
			}
		},
		computed: {
			isSendSMSEnable() {
				return this.smsCountDown <= 0 && this.tel && this.tel.length > 4;
			},
			getSendBtnText() {
				if (this.smsCountDown > 0) {
					return this.smsCountDown + '秒后';
				} else {
					return '发送验证码';
				}
			},
		},
		onLoad() {

			// #ifdef H5
			if (this.isWechat()) {
				this.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
			}
			// #endif

			// #ifdef MP-WEIXIN
			this.wxLogin()
			// #endif

			// #ifdef APP
			this.isAutoLogin()
			// #endif

			// #ifndef APP
			this.changeLoginWay(1)
			// #endif

			this.TIMLogin()
		},
		methods: {
			// 判断是否支持一键登陆
			isAutoLogin() {

				// #ifdef APP
				let _that = this
				uni.getProvider({ //获取可用的服务提供商
					service: 'oauth',
					success: function(res) {
						console.log(res.provider) // ['weixin', qq', 'univerify']
					}
				});
				uni.preLogin({ //预登录
					provider: 'univerify', //用手机号登录
					success(res) {
						_that.autoStatus = true
						console.log('预登录成功', res)
					},

					fail(err) { //预登录失败
						this.changeLoginWay(1)
						_that.autoStatus = false
						console.log('错误码：' + err.errCode)
						console.log(err.errMsg)
					}
				})
				// #endif


			},
			submitlogin() {
				let that = this
				uni.login({ //正式登录，弹出授权窗
					provider: 'univerify',

					univerifyStyle: { // 自定义登录框样式
						"fullScreen": false, // 是否全屏显示，true表示全屏模式，false表示非全屏模式，默认值为false。
						"backgroundColor": "#ffffff", // 授权页面背景颜色，默认值：#ffffff 
						"icon": {
							"path": "../../static/logo.png" // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo   
						},
						"phoneNum": {
							"color": "#5DACB1", // 手机号文字颜色 默认值：#000000   
						},
						"authButton": {
							"normalColor": "#5DACB1", // 授权按钮正常状态背景颜色 默认值：#3479f5  
							"highlightColor": "#5DACB1", // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）  
							"disabledColor": "#5DACB1", // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）  
							"textColor": "#ffffff", // 授权按钮文字颜色 默认值：#ffffff  
							"title": "本机号码一键登录" // 授权按钮文案 默认值：“本机号码一键登录”  
						}
					},
					success(res) { // 正式登录成功
						console.log(res.authResult); // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
						// 在得到access_token后，通过callfunction调用云函数
						uniCloud.callFunction({
							name: 'getPhoneNumber', // 云函数名称
							data: { //传给云函数的参数
								'access_token': res.authResult.access_token, // 客户端一键登录接口返回的access_token
								'openid': res.authResult.openid // 客户端一键登录接口返回的openid
							},
							success(callRes) {
								console.log("响应", callRes.result.data.data)
								let res = callRes.result.data.data
								if (res.toRegister) {
									uni.navigateTo({
										url: '/pages/register/register?tel=' + res.token
									});
								} else {
									uni.setStorageSync(ACCESS_TOKEN, res.token)
									uni.switchTab({
										url: '/pages/self/self'
									});
								}

							},
							fail(callErr) {
								console.log('调用云函数出错', callErr)
							},
							complete() {
								uni.closeAuthView() //关闭授权登录界面
							}
						})
					},
					fail(err) { // 正式登录失败
						console.log(err.errCode)
						console.log(err.errMsg)
						uni.closeAuthView() //关闭授权登录界面
					}
				})
			},


			accountLogin() {
				http.post('/login/account', {
					tel: this.tel,
					password: this.password
				}).then(res => {
					if (res.success) {
						uni.setStorageSync(ACCESS_TOKEN, res.data)
						uni.switchTab({
							url: '/pages/self/self'
						});
					}
				})
			},

			phoneLogin() {
				http.post('/login/tel', {
					tel: this.tel,
					code: this.code
				}).then(res => {
					if (res.success) {
						if (res.data.toRegister) {
							uni.navigateTo({
								url: '/pages/register/register?tel=' +
									this.tel
							})
						} else {
							uni.setStorageSync(ACCESS_TOKEN, res.data.token);
							uni.showToast({
								icon: 'success',
								title: '登录成功',
								duration: 500
							}).then(() => {
								uni.switchTab({
									url: '/pages/self/self'
								})
							})
						}
					}
				})
			},


			changeLoginWay(way) {
				this.way = way
			},


			onSMSSend() {
				if (this.smsCountDown > 0)
					return;
				let smsParams = {
					tel: this.tel,
					email: ""
				};
				let checkPhone = new RegExp(/^1([3-9])\d{9}$/);
				if (!smsParams.tel || smsParams.tel.length === 0) {
					this.$message.error('手机号不能为空');
					return false;
				}
				if (!checkPhone.test(smsParams.tel)) {
					this.$message.error('手机号不合法');
					return false;
				}
				console.log(smsParams)
				this.$api.sendVerificationCode(smsParams)
				this.smsCountDown = 60;
				this.startSMSTimer();
			},
			startSMSTimer() {
				this.smsCountInterval = setInterval(() => {
					this.smsCountDown--;
					if (this.smsCountDown <= 0) {
						clearInterval(this.smsCountInterval);
					}
				}, 1000);
			},




			wxLogin() {

				uni.showLoading({
					title: '登录中'
				});

				// #ifdef H5
				this.getWeChatCode()
				// #endif

				// #ifdef APP
				let that = this
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						console.log(res.provider)
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								onlyAuthorize: true,
								success: function(loginRes) {
									console.log("直接响应", loginRes)

									that.$api.wxLogin({
											code: loginRes.code,
											loginType: "APP"
										})
										.then((res) => {
											console.log("最终响应", res)
											uni.hideLoading()
											if (res.data.toRegister) {
												uni.navigateTo({
													url: '/pages/register/register?unionId=' +
														res.data.unionId
												})
											} else {
												that.$tip.success('登录成功!')
												uni.setStorageSync(ACCESS_TOKEN, res.data);
												uni.switchTab({
													url: '../self/self'
												})
											}
										})
								}
							});
						}
					}
				});
				// #endif

				// #ifdef MP-WEIXIN
				let that = this
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						console.log(res.provider)
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									let code = loginRes.code
									that.$api.wxLogin({
											code: code,
											loginType: "MINI_APP"
										})
										.then((res) => {
											uni.hideLoading()
											if (res.data.toRegister) {
												uni.navigateTo({
													url: '/pages/register/register?unionId=' +
														res.data.unionId +
														"&miniOpenId=" + res.data
														.openId
												})
											} else {
												uni.setStorageSync(ACCESS_TOKEN, res.data
													.token);
												uni.switchTab({
													url: '/pages/self/self'
												})
											}
										})
								}
							});
						}
					}
				});
				// #endif
			},
			TIMLogin() {
				// 初始化完成后登录
				const userID = 'administrator'
				uni.$TUIKit.login({
					userID,
					userSig: genTestUserSig(userID).userSig
				}).then((imResponse) => {
					console.log(imResponse.data); // 登录成功
				}).catch(function(imError) {
					console.warn('login error:', imError); // 登录失败的相关信息
				});
			},



			//方法：用来判断是否是微信内置的浏览器
			isWechat() {
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			//方法:用来提取code
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
					[, ''
					])[1]
					.replace(/\+/g, '%20')) || null
			},
			//检查浏览器地址栏中微信接口返回的code
			checkWeChatCode() {
				let code = this.getUrlCode('code')
				// uni.showToast({
				// 	title: `微信code=${code}`
				// })
				if (code && code != "") {
					this.getOpenidAndUserinfo(code)
				}
			},

			getWeChatCode() {
				let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				let appid = 'wx4ca3f69146306fd9'

				//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				window.location.href =
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
					appid +
					"&redirect_uri=" +
					local +
					"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			},
			//把code传递给后台接口，静默登录
			getOpenidAndUserinfo(code) {
				this.$api.wxLogin({
					code: code,
					loginType: "MP"
				}).then((res) => {
					uni.setStorageSync(ACCESS_TOKEN, res.data.token);
					uni.showToast({
						icon: 'success',
						title: '登录成功',
						duration: 500
					}).then(() => {
						uni.switchTab({
							url: '/pages/self/self'
						})
					})
				})
			},
		}
	}
</script>

<style>
	.content {
		background: #FFFFFF;
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.avatorWrapper {
		height: 30vh;

		/* #ifdef H5 */
		height: 25vh;
		/* #endif */

		width: 100vw;
		display: flex;
		justify-content: center;
		align-items: flex-end;
	}

	.avator {
		width: 300rpx;
		height: 300rpx;
		overflow: hidden;
		border-radius: 20rpx;
	}

	.avator .img {
		width: 100%
	}

	.form {
		margin-top: 100rpx;
	}

	.inputWrapper {
		width: 600rpx;
		height: 120rpx;
		background: white;
		border-radius: 20rpx;
		overflow: hidden;
		box-sizing: border-box;
		margin-top: 30rpx;
	}

	.inputWrapper .input {
		width: 520rpx;
		padding: 0 40rpx;
		height: 100%;
		border-radius: 20rpx;
		font-size: 15px;
	}

	.loginBtn {
		width: 600rpx;
		height: 100rpx;
		background: #5DACB1;
		border-radius: 20rpx;
		margin-top: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;

	}

	.loginBtn .btnValue {
		color: white;
	}

	.forgotBtn {
		text-align: center;
		color: gray;
		font-size: 15px;
		margin-top: 20px;
	}

	.changeWayBtn {
		width: 580rpx;
		margin-left: 10rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;


		color: gray;
		font-size: 15px;
		margin-top: 20px;
		height: 50rpx;
	}
</style>
